<template>
  <el-container>
    <el-header>
      <TopBar />
    </el-header>
    <el-main class="el-main">
      <div class="club-manage-container">
        <!-- 页面标题 -->
        <div class="page-header">
          <h1>{{ clubData.clubname }} - 社团管理</h1>
          <el-button type="primary" @click="goToClubPage">返回社团主页</el-button>
        </div>

        <!-- 管理导航 -->
        <div class="manage-nav">
          <router-link
            :to="`/club/${clubId}/manage/info`"
            custom
            v-slot="{ navigate, isActive }"
          >
            <div
              class="nav-item"
              :class="{ active: isActive }"
              @click="navigate"
            >
              <i class="el-icon-setting"></i>
              基本信息管理
            </div>
          </router-link>
          <router-link
            :to="`/club/${clubId}/manage/members`"
            custom
            v-slot="{ navigate, isActive }"
          >
            <div
              class="nav-item"
              :class="{ active: isActive }"
              @click="navigate"
            >
              <i class="el-icon-user"></i>
              成员管理
            </div>
          </router-link>


          <router-link
            :to="`/club/${clubId}/manage/applications`"
            custom
            v-slot="{ navigate, isActive }"
          >
            <div
              class="nav-item"
              :class="{ active: isActive }"
              @click="navigate"
            >
              <i class="el-icon-document"></i>
              申请管理
              <el-badge
                v-if="pendingApplicationsCount > 0"
                :value="pendingApplicationsCount"
                class="application-badge"
              />
            </div>
          </router-link>

          <router-link
            :to="`/club/${clubId}/manage/activities`"
            custom
            v-slot="{ navigate, isActive }"
          >
            <div
              class="nav-item"
              :class="{ active: isActive }"
              @click="navigate"
            >
              <i class="el-icon-time"></i>
              活动管理
            </div>
          </router-link>

          <router-link
            :to="`/club/${clubId}/manage/posts`"
            custom
            v-slot="{ navigate, isActive }"
          >
            <div
              class="nav-item"
              :class="{ active: isActive }"
              @click="navigate"
            >
              <i class="el-icon-s-comment"></i>
              帖子管理
            </div>
          </router-link>
        </div>

        <!-- 内容区域 -->
        <div class="manage-content">
          <router-view :club-id="clubId"></router-view>
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from '../../stores/userStore'
import { ElMessage } from 'element-plus'
import TopBar from '../../components/TopBar.vue'
import axios from 'axios'

// 获取路由和用户信息
const route = useRoute()
const router = useRouter()
const userStore = useStore()

// 获取社团ID
const clubId = route.params.id

// 社团数据
const clubData = ref({
  id: clubId,
  clubname: '加载中...',
  description: '',
  admin: [],
  members: [],
  joinApplications: [],
  exitApplications: []
})

// 待处理申请数量
const pendingApplicationsCount = computed(() => {
  // 加入和退出申请中status为pending的数量
  const joinPending = clubData.value.joinApplications?.filter(app => app.status === 'pending').length || 0
  const exitPending = clubData.value.exitApplications?.filter(app => app.status === 'pending').length || 0
  return joinPending + exitPending
})

// 返回社团主页
const goToClubPage = () => {
  router.push(`/club/${clubId}`)
}

// 加载社团数据
const loadClubData = async () => {
  try {
    // 从API获取社团数据
    const response = await axios.get(`http://localhost:5000/clubs/${clubId}`);

    if (response.data) {
      // 更新社团基本信息
      clubData.value = {
        ...response.data,
        id: clubId,
        clubname: response.data.clubname || '未命名社团',
      };

      // 如果需要单独获取申请列表
      loadApplicationsCount();
    }
  } catch (error) {
    console.error('加载社团数据失败:', error);
    ElMessage.error('加载社团数据失败');
  }
}

// 加载申请数量
const loadApplicationsCount = async () => {
  try {
    // 获取加入申请
    const joinResponse = await axios.get(`http://localhost:5000/clubs/${clubId}/applications?type=join`);
    if (joinResponse.data) {
      clubData.value.joinApplications = joinResponse.data;
    }

    // 获取退出申请
    const exitResponse = await axios.get(`http://localhost:5000/clubs/${clubId}/applications?type=exit`);
    if (exitResponse.data) {
      clubData.value.exitApplications = exitResponse.data;
    }
  } catch (error) {
    console.error('加载申请数据失败:', error);
  }
}

// 验证用户权限
const checkPermission = async () => {
  try {
    // 获取用户信息
    const token = localStorage.getItem('token');
    if (!token) {
      ElMessage.warning('请先登录');
      router.push('/login');
      return false;
    }

    // 检查用户是否是社团管理员
    const clubResponse = await axios.get(`http://localhost:5000/clubs/${clubId}`);
    const club = clubResponse.data;

    if (!club) {
      ElMessage.warning('社团不存在');
      router.push('/clubs');
      return false;
    }

    // 检查当前用户ID是否在社团的admin列表中
    const isAdmin = club.admin && Array.isArray(club.admin)
      ? club.admin.includes(userStore.user._value._id)
      : club.admin === userStore.user._value._id;

    if (!isAdmin) {
      ElMessage.warning('您没有权限管理该社团');
      router.push(`/club/${clubId}`);
      return false;
    }

    return true;
  } catch (error) {
    console.error('权限验证失败:', error);
    ElMessage.error('验证权限失败');
    router.push(`/club/${clubId}`);
    return false;
  }
}

onMounted(async () => {
  if (await checkPermission()) {
    loadClubData();
  }
})
</script>

<style scoped>
.el-main {
  padding: 0;
  background-color: #121212;
  /* min-height: 100vh; */
}

.club-manage-container {
  padding: 20px;
  /* margin-top: 60px; */
  color: #ffffff;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
}

.manage-nav {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  padding: 10px 0;
  border-bottom: 1px solid #333;
}

.nav-item {
  padding: 10px 16px;
  border-radius: 4px;
  cursor: pointer;
  color: #b0bec5;
  transition: background-color 0.3s, color 0.3s;
  display: flex;
  align-items: center;
  position: relative;
}

.nav-item:hover {
  background-color: #28232e;
  color: #ffffff;
}

.nav-item.active {
  background-color: #1f1b24;
  color: #00aeff;
  border-left: 3px solid #00aeff;
}

.nav-item i {
  font-size: 18px;
}

.manage-content {
  background-color: #1f1b24;
  border-radius: 8px;
  padding: 20px;
  min-height: 70vh;
}

.application-badge {
  position: absolute;
  top: -6px;
  right: -6px;
}
</style>
